app.service('common', function($http, $location, $sce){
    var that    = this;

    //获取get参数
    this.getUrlParam    = function(par, defaultVal){
        var defaultVal  = defaultVal ? defaultVal : false;
        var localUrl = document.location.href; 
        var get = localUrl.indexOf(par + "=");
        if(get == -1){
            return defaultVal;   
        }   
        //截取字符串
        var getPar = localUrl.slice(par.length + get + 1);    
        //判断截取后的字符串是否还有其他get参数
        var nextPar = getPar.indexOf("&");
        if(nextPar != -1){
            getPar = getPar.slice(0, nextPar);
        }
        return getPar ? getPar : defaultVal;
    }

    //判断数组中是否存在某值
    this.inArray    = function(value, array){
        for(var k in array){
            if(value == array[k])  return true;
        }
        return false;
    }

    //信任HTML
    this.trustAsHtml    = function(type, info, isList){
        if(type === false){
            return $sce.trustAsHtml(info);
        }
        switch(type){
            case 'activity':
                if(isList == false){
                    info.introduct  = $sce.trustAsHtml(info.introduct);
                    info.content    = $sce.trustAsHtml(info.content);
                    info.i_header   = $sce.trustAsHtml(info.i_header);
                    info.i_footer   = $sce.trustAsHtml(info.i_footer);
                    info.ii_cont    = $sce.trustAsHtml(info.ii_cont);
                    info.iii_cont   = $sce.trustAsHtml(info.iii_cont);
                }
            break;
        }

        // return info;
    }

    //添加留言
    this.writeLeaveMsg  = function(title, param){
        S('leavemsg_title', title);
        S('leavemsg_param', param);

        that.logAnchor();

        $location.path('/LeaveMsg/add');
    }

    //记录返回点
    this.logAnchor  = function(anchor){
        var anchor  = anchor ? anchor : $location.path();
        S('the_anchor', anchor);
    }

    //返回记录点
    this.backAnchor     = function(compel){
        var anchor  = S('the_anchor') ? S('the_anchor') : '/Course/index';
        if(!compel){
            $location.path(anchor);
        }else{
            window.open('/wechat/html/index.html?code='+config.code+'&#'+anchor, '_self');
        }
    }

    //初始化音频
    this.initAudio  = function(element, audioInfo, pic){
        var pic    = pic ? pic : config.web_logo;
        var audio = new APlayer({
            element: element,
            narrow: false,
            showlrc: false,
//            preload : 'none',
            mode    : 'order',
            music: {
                'title'   : audioInfo.title,
                'author'  : audioInfo.author,
                'url'     : audioInfo.audio,
                'pic'     : pic
            }
        });

        return audio;
    }

    //错误处理
    this.dealError   = function(info){
        console.log(info);
    	switch(info.code){
    	    case 102:
                that.doAlert(info.data);
                WeixinJSBridge.call('closeWindow');
            break;
    	    case 104:
        		that.doAlert(info.data);
        		WeixinJSBridge.call('closeWindow');
    	    break;
            //完善用户信息
            case 300:
                that.doAlert(info.data);
                $location.path('/Sole/user_info');
            break;
            //绑定手机号
            case 302:
                that.logAnchor();
                that.doAlert(info.data);
                $location.path('/User/bindUsername');
            break;
            //充值VIP
            case 304:
                that.logAnchor();
                that.doAlert(info.data);
                $location.path('/Vip/purchase');
            break;
    	    default:
    		    that.doAlert(info.data);
    	    break;
     	}
    }

    //数据分页处理
    this.dealListInfo   = function(info, list, page){
        var isEnd   = true;
        try{
            if(info.length < config.page_count){
                isEnd   = true;
            }else{
                isEnd   = false;
            }
        }catch(e){ isEnd   = true; }

        if(page == 1)   list.length = 0;
        
        for(var k in info){
            list.push(info[k]);
        }

        return isEnd;
    }

    //信息提醒
    this.doAlert    = function(msg){
        alert(msg);
    }

    //设置网站标题
    this.setTitle   = function(title){
        $('title').html(title);
    }

    //获取用户信息
    this.getUserInfo    = function(callback){
        var userInfo    = S('user_info');
        if(userInfo){
            console.log('read cached!');
            callback(userInfo);
            return true;
        }

        var url     = config.prefix_url+'/user/index?code='+config.code;
        $http.get(url).success(function(info){
            console.log('not read cached!');
            if(info.code == 1){
                userInfo    = info.data;
                S('user_info', userInfo);
                callback(userInfo);
            }else{
                that.dealError(info);
            }
        });
    }

    //获取平台配置信息
    this.getPlatConfig  = function(callback){
        var platConfig  = S('plat_config');
        if(platConfig){
            console.log('read cached!');
            callback(platConfig);
        }else{
            console.log('not reat cached!');
            var url     = config.prefix_url+'/index/getPlatConfig?code='+config.code;
            $http.get(url).success(function(info){
                if(info.code != 1){
                    that.dealError(info);
                }else{
                    platConfig  = info.data.config;
                    S('plat_config', platConfig);
                    callback(platConfig);
                }
            });
        }
    }
});

app.service('wechat', function($http, $location, common){
    //微信配置
    this.wxConfig   = function(callback){
        //注册用户分享链接
        if(!config.wx_share_link){
            common.getUserInfo(function(info){
                //注册欣乐土分享链接
                config.wx_share_link    = 'index.html?'+
                    '&param='+base64encode('user_id='+user.id)+
                    '&#/Share/2dcode';
            })
        }

        var nowUrl  = window.location.href;
        if(nowUrl.indexOf('#') > -1)
            nowUrl  = nowUrl.substring(0, nowUrl.indexOf('#'));
        
        var url     = config.prefix_url+'/Public/createWxJsSdk?url='+base64encode(nowUrl);

        $http.get(url).success(function(info){
            if(info.code != 1){
                common.dealError(info);
            }else{
                var data    = info.data;
                var _wxConfig   = {
                    'debug'     : false,
                    'appId' : data.app_id,
                    'timestamp' : data.timestamp,
                    'nonceStr'  : data.nonce_str,
                    'signature' : data.signature,
                    'jsApiList' : ['onMenuShareAppMessage', 'onMenuShareTimeline', 'showMenuItems', 'hideOptionMenu']
                }
                wx.config(_wxConfig);
                wx.ready(function(){
                    //隐藏微信菜单
                    wx.hideOptionMenu();
                    if(callback) callback();
                });
                wx.error(function(res){
                    console.log(res);
                });
            }
        });
    }

    //微信分享给朋友
    this.wxShareFriend  = function(title, desc, link, imgUrl, callback){
        title   = title ? title : config.wx_share_title;
        desc    = desc ? desc : config.wx_share_desc;
        link    = link ? link : config.wx_share_link;
        imgUrl  = imgUrl ? imgUrl : config.wx_share_img;

        wx.onMenuShareAppMessage({
            title: title,
            desc: desc,
            link: link,
            imgUrl: imgUrl,
            type: 'link',
            success: function () { 
                // that.shareSuccess();
                callback(true);
            },
            cancel: function () { 
                callback(false);
                console.log('分享失败!');
            }
        });
    }

    //微信分享朋友圈
    this.wxShareTimeLine    = function(title, link, imgUrl, callback){
        title   = title ? title : config.wx_share_title;
        link    = link ? link : config.wx_share_link;
        imgUrl  = imgUrl ? imgUrl : config.wx_share_img;

        wx.onMenuShareTimeline({
            title: title,
            link: link,
            imgUrl: imgUrl,
            success: function () { 
                callback(true);
                // that.shareSuccess();
            },
            cancel: function () { 
                callback(false);
                console.log('share error!');
            }
        });
    }

    //分享成功通知服务端
    this.shareSuccess   = function(){
        common.getUserInfo(function(user){
            var url     = config.prefix_url+'/Share/shareSuccess?'+
                '&param='+base64encode('user_id='+user.id);
            $http.get(url).success(function(info){
                console.log('share success:');
                console.log(info);
            });
        });
    }

    //发起微信支付
    this.wxPay  = function(appId, timeStamp, nonceStr, package, signType, paySign, callback){
        var timeStamp   = JSON.stringify(timeStamp);
        var payConfig   = {
            'appId' : appId,
            'timeStamp' : timeStamp,
            'nonceStr'  : nonceStr,
            'package'   : package,
            'signType'  : signType,
            'paySign'   : paySign
        }
        function onBridgeReady(){
            WeixinJSBridge.invoke('getBrandWCPayRequest', payConfig, function(res){
                if(res.err_msg == 'get_brand_wcpay_request:ok'){
                    console.log('支付成功!');
                    callback();
                }else{
                    console.log('支付失败!');
                }
            });
        }

        if (typeof WeixinJSBridge == "undefined"){
           if( document.addEventListener ){
               document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
           }else if (document.attachEvent){
               document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
               document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
           }
        }else{
           onBridgeReady();
        }
    }

    var that    = this;
});

app.service('course', function($rootScope, $location, $http, common, wechat){
    //听课
    this.listen     = function(playType, courseId, chapterId){
        S('play_course_id', courseId);
        S('play_chapter_id', chapterId);
        
        var playType    = parseInt(playType);
        switch(playType){
            //音频+图片类型
            case 1:
                $location.path('/Course/playaudio');
            break;
            default: 
                common.doAlert('未知播放类型!'+playType);
            break;
        }
    }

    //购买课程
    this.buy_course     = function(courseId, callback){
        var url     = config.prefix_url+'/Course/buyByMoney?code='+config.code+'&course_id='+courseId;
        $http.get(url).success(function(info){
            console.log(info);
            if(info.code == 1){
                var data    = info.data;
                wechat.wxPay(
                    data.appId,
                    data.timeStamp,
                    data.nonceStr,
                    data.package,
                    data.signType,
                    data.paySign,
                    callback
                );
            }else if(info.code == 302){
                common.doAlert(info.data);
                callback();
            }else{
                common.dealError(info);
            }
        });
    }
});
